"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const RSATool_1 = __importDefault(require("../../lib/RSATool"));
const configTool_1 = __importDefault(require("../../com/configTool"));
function TokenAuthorityHandler() {
    return async (ctx, next) => {
        const token_get = ctx.request.query?.token;
        const token_body = ctx.request.body?.token;
        const token_header = ctx.request.header?.token;
        const token = token_get || token_body || token_header;
        if (decodeURI(ctx.request.url).includes('/AuthorizeServer/login')) {
            await next();
        }
        else if (decodeURI(ctx.request.url) === '/') {
            await next();
            ctx.status = 200;
            ctx.body = { code: 200, message: '服务已启动成功...版本号：' + configTool_1.default.baseConfig.version, desc: new Date().toISOString() };
        }
        else if (token) {
            try {
                let plaintext = RSATool_1.default.decrypt(token, configTool_1.default.baseConfig.privateDer);
                let userObj = JSON.parse(plaintext);
                if (new Date(userObj.token_expired_date).getTime() < (new Date()).getTime()) {
                    ctx.status = 401;
                    ctx.body = { code: 401, message: 'Token 已过期，请重新登录', desc: `Token 已过期，请重新登录` };
                }
                else if (userObj.ip !== ctx.request.ip) {
                    ctx.body = { code: 401, message: '未授权的IP地址用户', desc: `请重新登录` };
                }
                else {
                    await next();
                }
            }
            catch (e) {
                ctx.status = 401;
                ctx.response.body = { code: 401, message: 'Token 错误', desc: `Token 错误` };
            }
        }
        else {
            ctx.response.status = 401;
            ctx.response.body = {
                code: 401, message: '参数缺少 Token', desc: `参数缺少 Token`
            };
        }
    };
}
exports.default = TokenAuthorityHandler;
